import paramiko
from config import config
from api.db_handler import DBHandler
import re


class SSHHandler:

    def __init__(self, table=config.mysql_table
                 , database=config.mysql_database, host=config.ssh_host, port=config.ssh_port,
                 user=config.ssh_user,
                 password=config.ssh_password
                 ):
        self.ssh_clint = paramiko.SSHClient()
        self.ssh_clint.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        self.ssh_clint.connect(host, port, user, password)
        self.database = database
        self.table = table

    # 备份数据库表
    def back(self):
        self.ssh_clint.exec_command(
            f'{config.mysql_path} -u {config.ssh_user} -p{config.ssh_password} {self.database} {self.table} > {config.table_path}')

    # 恢复数据库表
    @staticmethod
    def restore():
        with open(config.users_table_path, 'r', encoding='utf-8') as f:
            insert_table = ''.join(re.findall('INSERT.+.;', f.read()))
            DBHandler().query(insert_table)

    # 初始化数据库表
    @staticmethod
    def initialize_table(sql):
        DBHandler().query(sql)

    def clone(self):
        self.ssh_clint.close()


if __name__ == '__main__':
    ssh = SSHHandler('tp_users')
    # ssh.initialize_table('DELETE FROM tp_users')
    ssh.restore()
    ssh.clone()
